package com.example.weight.greenSeasons.flocculation;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.example.weight.greenSeasons.compost.duifeigongyi;
import com.example.weight.greenSeasons.compost.duifeiyuebaoyang;
import com.example.weight.greenSeasons.deodorization.DeodorizationTower;
import com.example.weight.greenSeasons.waterDeal.DeodorizationTable;
import com.example.weight.util.Utility;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import net.cachapa.expandablelayout.ExpandableLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

public class xuninggongyi extends AppCompatActivity {
    private ExpandableLayout expand_1;
    private ExpandableLayout expand_2;
    private ExpandableLayout expand_3;
    private ExpandableLayout expand_4;
    private ExpandableLayout expand_5;
    private Button textView1;
    private Button textView2;
    private Button textView3;
    private Button textView4;
    private Button textView5;
    private TitleBar titleBar;
    private String name,factory;

    Calendar calendar= Calendar.getInstance(Locale.CHINA);

    //絮凝日期
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    private SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("HH:mm");// HH:mm:ss
    Date xuNingDate = new Date(System.currentTimeMillis());
    private TextView xuNing_date;
    SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy/MM/dd HH:mm");

    //絮凝时间
    private TextView xuNing_time;
    //药泵流量计读数,泥泵流量计读数 共8个
    private EditText drugPumpFlow1;
    private EditText mudPumpFlow1;
    private EditText drugPumpFlow2;
    private EditText mudPumpFlow2;
    private EditText drugPumpFlow3;
    private EditText mudPumpFlow3;
    private EditText drugPumpFlow4;
    private EditText mudPumpFlow4;
    private EditText paikongTime;
    //大调节池液位
    private EditText tankLiquidLevel;
    //絮凝剂用量
    private EditText flocculantNumber;
    //三氯化铁用量
    private EditText ironNumber;
    //备注
    private EditText remark;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_xuninggongyi);

        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");

        expand_1=findViewById(R.id.expandable_1);
        expand_2=findViewById(R.id.expandable_2);
        expand_3=findViewById(R.id.expandable_3);
        expand_4=findViewById(R.id.expandable_4);
        expand_5=findViewById(R.id.expandable_5);
        textView1=findViewById(R.id.button_1);
        textView2=findViewById(R.id.button_2);
        textView3=findViewById(R.id.button_3);
        textView4=findViewById(R.id.button_4);
        textView5=findViewById(R.id.button_5);

        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {

            @Override
            public void onLeftClick(View v) {
                xuninggongyi.this.finish();
            }

            @Override
            public void onTitleClick(View v) { }

            @Override
            public void onRightClick(View v) { }
        });

        /**
         * 显示设置日期
         */
        xuNing_date = findViewById(R.id.xuNing_date);
        xuNing_date.setText(simpleDateFormat.format(xuNingDate));
        //时间
        xuNing_time = (TextView) findViewById(R.id.xuNing_time);
        xuNing_time.setText(simpleDateFormat1.format(xuNingDate));
//        xuNing_time.setOnClickListener(this);
        /**
         *8个流量计读数
         */
        //药泵流量计读数1
        drugPumpFlow1 = findViewById(R.id.drugPumpFlow1);
        //泥泵流量计读数1
        mudPumpFlow1 = findViewById(R.id.mudPumpFlow1);
        //药泵流量计读数2
        drugPumpFlow2 = findViewById(R.id.drugPumpFlow2);
        //泥泵流量计读数2
        mudPumpFlow2 = findViewById(R.id.mudPumpFlow2);
        //药泵流量计读数3
        drugPumpFlow3 = findViewById(R.id.drugPumpFlow3);
        //泥泵流量计读数3
        mudPumpFlow3 = findViewById(R.id.mudPumpFlow3);
        //药泵流量计读数4
        drugPumpFlow4 = findViewById(R.id.drugPumpFlow4);
        //泥泵流量计读数4
        mudPumpFlow4 = findViewById(R.id.mudPumpFlow4);

        //大调节池液位
        tankLiquidLevel = findViewById(R.id.tankLiquidLevel);
        //絮凝剂用量
        flocculantNumber = findViewById(R.id.flocculantNumber);
        //三氯化铁用量
        ironNumber = findViewById(R.id.ironNumber);
        paikongTime = findViewById(R.id.paikong_time);
        //备注
        remark = findViewById(R.id.xuNing_remark);


        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/flocculationCraftSceneNew/findForm" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Date fromDate_paikongTime = new Date();
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            if (!jsonObject.isNull("data")) {
                                JSONObject data = jsonObject.getJSONObject("data");
                                Log.d("jy", data.toString());
                                String temp;
                                temp = data.getString("drugpumpflow1");
                                drugPumpFlow1.setHint(temp.equals("null")?"":temp);
                                temp = data.getString("mudpumpflow1");
                                mudPumpFlow1.setHint(temp.equals("null")?"":temp);
                                temp = data.getString("drugpumpflow2");
                                drugPumpFlow2.setHint(temp.equals("null")?"":temp);
                                temp = data.getString("mudpumpflow2");
                                mudPumpFlow2.setHint(temp.equals("null")?"":temp);
                                temp = data.getString("drugpumpflow3");
                                drugPumpFlow3.setHint(temp.equals("null")?"":temp);
                                temp = data.getString("mudpumpflow3");
                                mudPumpFlow3.setHint(temp.equals("null")?"":temp);
                                temp = data.getString("drugpumpflow4");
                                drugPumpFlow4.setHint(temp.equals("null")?"":temp);
                                temp = data.getString("mudpumpflow4");
                                mudPumpFlow4.setHint(temp.equals("null")?"":temp);
                                temp = data.getString("tankliquidlevel");
                                tankLiquidLevel.setHint(temp.equals("null")?"":temp);
                                temp = data.getString("flocculantnumber");
                                flocculantNumber.setHint(temp.equals("null")?"":temp);
                                temp = data.getString("ironnumber");
                                ironNumber.setHint(temp.equals("null")?"":temp);
                                temp = data.getString("bufferTank");
                                if (!temp.equals("null")){
                                    fromDate_paikongTime=simpleDateFormat2.parse(temp);
                                }
                                paikongTime.setHint(temp.equals("null")?"":simpleDateFormat2.format(fromDate_paikongTime));
                                temp = data.getString("remarks");
                                remark.setHint(temp.equals("null")?"":temp);
                                Toast.makeText(xuninggongyi.this,
                                        "今日已填写此表", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException | ParseException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(xuninggongyi.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }
    public void show1(View view) {
        if (expand_1.isExpanded()){
            textView1.setText("+ 1#");
        }else{
            textView1.setText("- 1#");
        }

        expand_1.toggle();
    }
    public void show2(View view) {
        if (expand_2.isExpanded()){
            textView2.setText("+ 2#");
        }else{
            textView2.setText("- 2#");
        }

        expand_2.toggle();
    }
    public void show3(View view) {
        if (expand_3.isExpanded()){
            textView3.setText("+ 3#");
        }else{
            textView3.setText("- 3#");
        }

        expand_3.toggle();
    }
    public void show4(View view) {
        if (expand_4.isExpanded()){
            textView4.setText("+ 叠螺机");
        }else{
            textView4.setText("- 叠螺机");
        }

        expand_4.toggle();
    }
    public void show5(View view) {
        if (expand_5.isExpanded()){
            textView5.setText("+ 其他");
        }else{
            textView5.setText("- 其他");
        }

        expand_5.toggle();
    }
    
    @SuppressLint({"DefaultLocale", "SetTextI18n", "ResourceType"})
    public void selectPaikongTime(View view) {
        Calendar calendar = Calendar.getInstance();
        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new DatePickerDialog(this, 2, (view1, year, month, day) -> {
            // 更新EditText控件日期 小于10加0
            new TimePickerDialog(this, 2, (view11, hourOfDay, minute) -> {
                //  这个方法是得到选择后的 小时、分钟，分别对应着三个参数 —   hourOfDay、minute
                paikongTime.setText(new StringBuilder()
                        .append(year)
                        .append("/")
                        .append((month + 1) < 10 ? "0"
                                + (month + 1) : (month + 1))
                        .append("/")
                        .append((day < 10) ? "0" + day : day)
                        .append(" ")
                        .append(String.format("%02d",hourOfDay))
                        .append(":")
                        .append(String.format("%02d",minute)));
            },HOUR, MINUTE, true).show();
        },YEAR, MONTH, DAY).show();
    }
    //    选择日期
    @SuppressLint({"DefaultLocale", "ResourceType"})
    public void selectDate(View view){
        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);
        new DatePickerDialog(this, 2, (view1, year, month, day) -> {
            // 更新EditText控件日期 小于10加0
            xuNing_date.setText(new StringBuilder()
                    .append(year)
                    .append("-")
                    .append((month + 1) < 10 ? "0"+ (month + 1) : (month + 1))
                    .append("-")
                    .append((day < 10) ? "0" + day : day));
        },YEAR, MONTH, DAY).show();
    }
    @SuppressLint({"DefaultLocale", "ResourceType"})
    public void selectTime(View view){
        int HOUR = calendar.get(Calendar.HOUR_OF_DAY);
        int MINUTE = calendar.get(Calendar.MINUTE);
        new TimePickerDialog(this, 2, (view11, hourOfDay, minute) -> {
            // 更新EditText控件日期 小于10加0
            xuNing_time.setText(new StringBuilder()
                    .append(String.format("%02d",hourOfDay))
                    .append(":")
                    .append(String.format("%02d",minute)));
        },HOUR, MINUTE, true).show();
    }

    public void save(View view) {
        if (xuNing_time.getText().toString().equals("") &&
            drugPumpFlow1.getText().toString().equals("") &&
            mudPumpFlow1.getText().toString().equals("") &&
            drugPumpFlow2.getText().toString().equals("") &&
            mudPumpFlow2.getText().toString().equals("") &&
            drugPumpFlow3.getText().toString().equals("") &&
            mudPumpFlow3.getText().toString().equals("") &&
            drugPumpFlow4.getText().toString().equals("") &&
            mudPumpFlow4.getText().toString().equals("") &&
            tankLiquidLevel.getText().toString().equals("") &&
            flocculantNumber.getText().toString().equals("") &&
            ironNumber.getText().toString().equals("")) {
            Toast.makeText(this, "请填写相关信息", Toast.LENGTH_SHORT).show();
            return;
        }
        if (xuNing_time.getText().toString().equals("")) {
            Toast.makeText(this, "请填写时间", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!drugPumpFlow1.getText().toString().equals("") &&
            !Utility.isNumeric(drugPumpFlow1.getText().toString())) {
            Toast.makeText(this, "1#药泵流量格式错误", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!mudPumpFlow1.getText().toString().equals("") &&
                !Utility.isNumeric(mudPumpFlow1.getText().toString())) {
            Toast.makeText(this, "1#泥泵流量格式错误", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!drugPumpFlow2.getText().toString().equals("") &&
                !Utility.isNumeric(drugPumpFlow2.getText().toString())) {
            Toast.makeText(this, "2#药泵流量格式错误", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!mudPumpFlow2.getText().toString().equals("") &&
                !Utility.isNumeric(mudPumpFlow2.getText().toString())) {
            Toast.makeText(this, "2#泥泵流量格式错误", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!drugPumpFlow3.getText().toString().equals("") &&
                !Utility.isNumeric(drugPumpFlow3.getText().toString())) {
            Toast.makeText(this, "3#药泵流量格式错误", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!mudPumpFlow3.getText().toString().equals("") &&
                !Utility.isNumeric(mudPumpFlow3.getText().toString())) {
            Toast.makeText(this, "3#泥泵流量格式错误", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!drugPumpFlow4.getText().toString().equals("") &&
                !Utility.isNumeric(drugPumpFlow4.getText().toString())) {
            Toast.makeText(this, "4#药泵流量格式错误", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!mudPumpFlow4.getText().toString().equals("") &&
                !Utility.isNumeric(mudPumpFlow4.getText().toString())) {
            Toast.makeText(this, "4#泥泵流量格式错误", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!tankLiquidLevel.getText().toString().equals("") &&
                !Utility.isNumeric(tankLiquidLevel.getText().toString())) {
            Toast.makeText(this, "大调节池液位格式错误", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!flocculantNumber.getText().toString().equals("") &&
                !Utility.isNumeric(flocculantNumber.getText().toString())) {
            Toast.makeText(this, "絮凝剂用量格式错误", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!ironNumber.getText().toString().equals("") &&
                !Utility.isNumeric(ironNumber.getText().toString())) {
            Toast.makeText(this, "三氯化铁用量格式错误", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) ->{
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/flocculationCraftSceneNew/addForm";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    //Toast.makeText(RepairTable.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");
                                        if (code.startsWith("2"))
                                            Toast.makeText(xuninggongyi.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(xuninggongyi.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(xuninggongyi.this,
                                    "保存失败" + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("date", xuNing_date.getText().toString());
                            map.put("bufferTank", paikongTime.getText().toString());
                            map.put("xuNing_time", xuNing_time.getText().toString());
                            map.put("drugPumpFlow1",drugPumpFlow1.getText().toString());
                            map.put("mudPumpFlow1", mudPumpFlow1.getText().toString());
                            map.put("drugPumpFlow2",drugPumpFlow2.getText().toString());
                            map.put("mudPumpFlow2", mudPumpFlow2.getText().toString());
                            map.put("drugPumpFlow3",drugPumpFlow3.getText().toString());
                            map.put("mudPumpFlow3", mudPumpFlow3.getText().toString());
                            map.put("drugPumpFlow4",drugPumpFlow4.getText().toString());
                            map.put("mudPumpFlow4", mudPumpFlow4.getText().toString());
                            map.put("tankLiquidLevel", tankLiquidLevel.getText().toString());
                            map.put("flocculantNumber", flocculantNumber.getText().toString());
                            map.put("ironNumber", ironNumber.getText().toString());
                            map.put("recorder",name);
                            map.put("remarks", ((TextView) findViewById(R.id.xuNing_remark)).getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }

}